<?php
/**
 * Created by @baidu-aip
 * Author: ylang
 * Time: 2022/2/24 12:09
 */

namespace Hedgehog\BaiduAip\Api;

use Hedgehog\BaiduAip\Api;
use Hedgehog\BaiduAip\BaiduAip;
use Hanson\Foundation\AbstractAccessToken;
use Hedgehog\BaiduAip\Exception\Exception;

class AccessToken extends AbstractAccessToken
{

    public const API_URL = 'https://aip.baidubce.com/oauth/2.0/token';

    protected $prefix = 'baidu-aip.';

    protected $tokenJsonKey = 'access_token';

    protected $expiresJsonKey = 'expires_in';

    public function __construct(BaiduAip $app)
    {
        parent::__construct($app);
        $useAppConfig = $app->getAppConfig();
        $this->setAppId($useAppConfig['api_key']);
        $this->setSecret($useAppConfig['secret_key']);
    }

    public function getTokenFromServer()
    {
        $response = (new Api($this))
            ->getHttp()
            ->post(self::API_URL, [
                'grant_type' => 'client_credentials',
                'client_id' => $this->appId,
                'client_secret' => $this->secret,
            ]);

        return json_decode($response->getBody(), true);
    }


    public function checkTokenResponse($result)
    {
        isset($result['error']) and Exception::error($result['error_description']);
    }

}